"""API文档配置模块"""
from typing import List, Dict, Any
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
from fastapi.responses import HTMLResponse


def setup_api_docs(app: FastAPI) -> None:
    """配置API文档
    
    Args:
        app: FastAPI应用实例
    """
    # 自定义API元数据
    def custom_openapi() -> Dict[str, Any]:
        """自定义OpenAPI规范"""
        if app.openapi_schema:
            return app.openapi_schema
        
        openapi_schema = get_openapi(
            title="交易平台 API",
            version="1.0.0",
            description="交易平台的后端API文档，包含用户认证、商品管理、交易、钱包、消息等功能",
            routes=app.routes,
            tags=get_api_tags(),
        )
        
        # 添加JWT认证支持
        openapi_schema["components"]["securitySchemes"] = {
            "BearerAuth": {
                "type": "http",
                "scheme": "bearer",
                "bearerFormat": "JWT",
                "description": "请使用登录后获取的JWT Token进行认证"
            }
        }
        
        # 为所有需要认证的端点添加默认安全要求
        for path, methods in openapi_schema["paths"].items():
            for method, spec in methods.items():
                # 排除公开端点
                if not is_public_endpoint(path, method):
                    if "security" not in spec:
                        spec["security"] = [{"BearerAuth": []}]
        
        app.openapi_schema = openapi_schema
        return app.openapi_schema
    
    # 覆盖默认的openapi方法
    app.openapi = custom_openapi
    
    # 添加自定义的Swagger UI
    @app.get("/docs", include_in_schema=False)
    async def custom_swagger_ui_html() -> HTMLResponse:
        """自定义Swagger UI页面"""
        return get_swagger_ui_html(
            openapi_url=app.openapi_url,
            title=app.title + " - Swagger UI",
            oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
            swagger_js_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js",
            swagger_css_url="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css",
        )
    
    # 添加自定义的ReDoc
    @app.get("/redoc", include_in_schema=False)
    async def redoc_html() -> HTMLResponse:
        """自定义ReDoc页面"""
        return get_redoc_html(
            openapi_url=app.openapi_url,
            title=app.title + " - ReDoc",
            redoc_js_url="https://unpkg.com/redoc@next/bundles/redoc.standalone.js",
        )
    
    # 添加API介绍页面
    @app.get("/api", include_in_schema=False)
    async def api_home() -> HTMLResponse:
        """API主页"""
        return HTMLResponse(
            content="""
            <!DOCTYPE html>
            <html>
            <head>
                <title>交易平台 API</title>
                <style>
                    body {
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
                        max-width: 800px;
                        margin: 0 auto;
                        padding: 20px;
                        line-height: 1.6;
                    }
                    h1 {
                        color: #333;
                        text-align: center;
                    }
                    h2 {
                        color: #444;
                        margin-top: 30px;
                    }
                    .card {
                        background: #f8f9fa;
                        border-radius: 8px;
                        padding: 20px;
                        margin: 20px 0;
                        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                    }
                    .btn {
                        display: inline-block;
                        background: #007bff;
                        color: white;
                        padding: 10px 20px;
                        border-radius: 4px;
                        text-decoration: none;
                        font-weight: bold;
                    }
                    .btn:hover {
                        background: #0056b3;
                    }
                    .btn-redoc {
                        background: #8e24aa;
                    }
                    .btn-redoc:hover {
                        background: #6a1b9a;
                    }
                    .endpoint-list {
                        display: grid;
                        grid-template-columns: 1fr 1fr;
                        gap: 10px;
                    }
                    .endpoint-item {
                        background: white;
                        padding: 10px;
                        border-radius: 4px;
                        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
                    }
                    .method {
                        font-weight: bold;
                        display: inline-block;
                        width: 80px;
                    }
                    .GET { color: #28a745; }
                    .POST { color: #007bff; }
                    .PUT { color: #ffc107; }
                    .DELETE { color: #dc3545; }
                    .tag {
                        display: inline-block;
                        background: #e9ecef;
                        padding: 2px 8px;
                        border-radius: 12px;
                        font-size: 0.8rem;
                        margin-left: 5px;
                    }
                </style>
            </head>
            <body>
                <h1>交易平台 API</h1>
                
                <div class="card">
                    <h2>欢迎使用交易平台 API</h2>
                    <p>本API提供了交易平台的所有后端功能接口，包括用户认证、商品管理、交易、钱包、消息等功能。</p>
                    <p>API版本: 1.0.0</p>
                    <div style="margin-top: 20px;">
                        <a href="/docs" class="btn">Swagger UI文档</a>
                        <a href="/redoc" class="btn btn-redoc" style="margin-left: 10px;">ReDoc文档</a>
                    </div>
                </div>
                
                <div class="card">
                    <h2>快速开始</h2>
                    <h3>1. 获取认证令牌</h3>
                    <p>使用 <code>POST /auth/login</code> 接口获取JWT令牌。</p>
                    
                    <h3>2. 使用API</h3>
                    <p>在请求头中添加 <code>Authorization: Bearer {token}</code> 来访问受保护的API。</p>
                </div>
                
                <div class="card">
                    <h2>主要API端点</h2>
                    <div class="endpoint-list">
                        <div class="endpoint-item">
                            <span class="method GET">GET</span> <code>/api/products</code>
                            <span class="tag">products</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method POST">POST</span> <code>/api/products</code>
                            <span class="tag">products</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method GET">GET</span> <code>/api/products/{id}</code>
                            <span class="tag">products</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method POST">POST</span> <code>/api/transactions</code>
                            <span class="tag">transactions</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method GET">GET</span> <code>/api/wallet</code>
                            <span class="tag">wallet</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method POST">POST</span> <code>/api/wallet/recharge</code>
                            <span class="tag">wallet</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method GET">GET</span> <code>/api/messages</code>
                            <span class="tag">messages</span>
                        </div>
                        <div class="endpoint-item">
                            <span class="method POST">POST</span> <code>/api/reviews</code>
                            <span class="tag">reviews</span>
                        </div>
                    </div>
                </div>
                
                <div class="card">
                    <h2>认证</h2>
                    <p>本API使用JWT进行认证。获取令牌后，请在所有请求中包含<code>Authorization</code>头。</p>
                    <pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre>
                </div>
            </body>
            </html>
            """
        )


def get_api_tags() -> List[Dict[str, str]]:
    """获取API标签列表
    
    Returns:
        API标签列表
    """
    return [
        {"name": "auth", "description": "用户认证相关接口"},
        {"name": "users", "description": "用户管理相关接口"},
        {"name": "products", "description": "商品管理相关接口"},
        {"name": "categories", "description": "商品分类相关接口"},
        {"name": "transactions", "description": "交易相关接口"},
        {"name": "wallet", "description": "钱包和支付相关接口"},
        {"name": "messages", "description": "消息相关接口"},
        {"name": "reviews", "description": "评价相关接口"},
        {"name": "notifications", "description": "通知相关接口"},
    ]


def is_public_endpoint(path: str, method: str) -> bool:
    """检查端点是否为公开端点
    
    Args:
        path: API路径
        method: HTTP方法
        
    Returns:
        是否为公开端点
    """
    # 公开端点列表
    public_endpoints = [
        ("/auth/register", "post"),
        ("/auth/login", "post"),
        ("/auth/forgot-password", "post"),
        ("/auth/reset-password", "post"),
        ("/products", "get"),
        ("/products/", "get"),  # 处理带斜杠的路径
        ("/products/categories", "get"),
        ("/products/categories/", "get"),  # 处理带斜杠的路径
        ("/products/search", "get"),
        ("/products/search/", "get"),  # 处理带斜杠的路径
        ("/api", "get"),
        ("/docs", "get"),
        ("/redoc", "get"),
        ("/openapi.json", "get"),
    ]
    
    # 检查是否是公开端点
    # 移除路径中的参数部分，如 /products/{id} -> /products/
    import re
    clean_path = re.sub(r"/{[^/]+}", "/", path)
    
    # 检查是否是商品详情页（公开可读）
    product_detail_pattern = r"^/products/\d+"  # 匹配 /products/123 这样的路径
    if re.match(product_detail_pattern, path) and method.lower() == "get":
        return True
    
    # 检查是否是商品分类详情（公开可读）
    category_detail_pattern = r"^/products/categories/\d+"  # 匹配 /products/categories/123 这样的路径
    if re.match(category_detail_pattern, path) and method.lower() == "get":
        return True
    
    # 检查固定的公开端点
    return (clean_path, method.lower()) in public_endpoints